#!/usr/bin/python
#coding:utf-8

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import csvout
import sys

# driver = webdriver.Firefox()
driver = webdriver.PhantomJS()
# driver = webdriver.PhantomJS(executable_path="/home/gtmer/spider/phantomjs-2.1.1-linux-x86_64/bin/phantomjs")
driver.get('http://bbs.chinaunix.net/search.php?mod=forum')
time.sleep(3)
driver.find_element_by_id('scform_srchtxt').send_keys(sys.argv[1])
driver.find_element_by_id('scform_submit').click()
# time.sleep(10)
# try:
#     element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'lbPagerTitle')))
# finally:
time.sleep(5)
try:
    #只能找到element，不能定位到text()[2]
    res = driver.find_element_by_xpath('//*[@id="ct"]/div/div/div[1]/h2/em').text
except:
    #如果找不到就报错，此时数值为0
    num = 0
else:
    num = filter(lambda x: x.isdigit(), res)
finally:
    outdic = {
        'chinaunix_num': num
    }
    outli = ['chinaunix_num', num, driver.current_url]
    csvout.list2csv(outli)
    print(outli)
    driver.close()